package cn.zqy.demo2.day04.demo02;

import cn.zqy.demo.day06.Stu;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * HashMap存储自定义类型键值
 *     Map集合保证key是唯一的:
 *         作为key的元素,必须重写hashCode方法和equals方法,以保证key唯一
 * */
public class Demo01HashMapSaveStudent {
    public static void main(String[] args) {
        saveKeyString();
        System.out.println("=========");
        saveKeyStu();
    }


    /* HashMap存储自定义类型键值
        key:Student类型
            Student类就必须重写hashCode方法和equals方法,以保证key唯一*/
    private static void saveKeyStu() {
        HashMap<Student,String> map = new HashMap<>();
        map.put(new Student("小姐姐", 12),"A");
        map.put(new Student("大哥哥", 123),"V");
        map.put(new Student("老爷爷", 34),"H");
        map.put(new Student("小姐姐", 12),"J");
        System.out.println(map);

        Set<Student> set = map.keySet();

        Iterator<Student> ll = set.iterator();
        while(ll.hasNext()) {
            Student stu = ll.next();
            System.out.println(stu + "--->" + map.get(stu));
            //###*** 下面这种写法错误，ll.next()只要运行，就会把值取出，索引+1
           //System.out.println(ll.next() +"--->" + map.get(ll.next()));
        }
    }

    private static void saveKeyString() {
        HashMap<String, Student> map = new HashMap<>();
        map.put("A",new Student("小姐姐", 12));
        map.put("B",new Student("大哥哥", 45));
        map.put("C",new Student("老爷爷", 28));
        map.put("A",new Student("大妈妈", 67));
        //{A=Student{name='大妈妈', age=67}, B=Student{name='大哥哥', age=45}, C=Student{name='老爷爷', age=28}}
        System.out.println(map);  // 相同的key替换了前面的

        Set<Map.Entry<String, Student>> set = map.entrySet();
        for (Map.Entry<String, Student> stu : set) {
            System.out.println(stu.getKey() + "--->" + stu.getValue());
        }
    }
}
